<?php
namespace catchAdmin\externalGoods\model;

use catchAdmin\stock\model\WarehouseConfig;
use catcher\base\CatchModel;
use think\Exception;
use think\facade\Db;

class Areas extends CatchModel
{

    protected $name = 'db_syst_sync_areas';
    protected $field = [
        'id',
        'area_id',
        'pid',
        'area_name',
        'full_area_name',
        'supplier_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'tenant_id',
        'creator_id'
    ];

    public function parentCategory()
    {
        return $this->belongsTo(Areas::class, 'pid','area_id');
    }

    //获取库位全名
    public function getFullNameAttr()
    {
//        $fullName = $this->getData('name');
        $fullName = [$this->getData('area_name')];
        $parent = $this->parentCategory;
        while ($parent) {
            //$fullName = arr
            array_unshift($fullName,$parent->getData('area_name'));
//            $fullName = $parent->getData('name') . ' > ' . $fullName;
            $parent = $parent->parentCategory;
        }
        return $fullName;
    }

//    public function getFullIdAttr()
//    {
//        $fullName = $this->getData('id');
//        $parent = $this->parentCategory;
//        while ($parent) {
//            $fullName = $parent->getData('id') . ',' . $fullName;
//            $parent = $parent->parentCategory;
//        }
//        return $fullName;
//    }

    public function generateTree($data,$parent_id = 0)
    {
        $tree = [];
        $newData = array_combine(array_column($data,'area_id'),$data);

        foreach ($newData as $key => $datum) {
            if ($datum['pid'] == $parent_id) {
                //根节点直接把地址放到新数组中

                if(in_array($newData[$key]['area_name'],['重庆市','天津市','上海市','北京市'])){
                    $newData[$key]['full_area_name'] = $newData[$key]['area_name'] . $newData[$key]['area_name'];
                }else{
                    $newData[$key]['full_area_name'] = $newData[$key]['area_name'];
                }
                $tree[] = &$newData[$key];

            } else {
                //不是根节点的将自己的地址放到父级的child节点
                $newData[$key]['full_area_name'] = $newData[$datum['pid']]['full_area_name']  . $newData[$key]['area_name'];
                $newData[$datum['pid']]['children'][] = &$newData[$key];
                //$newData[$datum['parent_id']]['son'][] = &$newData[$key];
            }
        }
        return $tree;

//        $areasModel = (new Areas())->select()->toArray();
//
//        $ddd = (new Areas())->generateTree($areasModel);
//
//        $ddd1 = tree_to_list($ddd);
//
//
//        foreach ($ddd1 as $key => $value){
//            $fields = ['id', 'full_area_name'];
//            $ddd1[$key] = array_intersect_key($value, array_flip($fields));
//        }
//
//        //dd($ddd1);
//
//        $aa = new Areas();
//        $ress= $aa->saveAll($ddd1);
    }


}